<?php
// error_reporting(E_ALL);

header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Credentials: true");
header("Access-Control-Allow-Methods: OPTIONS, TRACE, GET, HEAD, POST");
header("Access-Control-Allow-Headers: Content-Type");
function mPrint($val = '') {
  echo json_encode($val);
}
function mPrintX($val = '') {
  echo json_encode($val);
  die;
}
function curl_https($url, $data = array(), $header = array(), $timeout = 30, $first = true) {
  $ch = curl_init();
  curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, $first); // 跳过证书检查 
  curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, $first);
  if ($first) curl_setopt($ch, CURLOPT_CAINFO, dirname(__FILE__) . '/cacert.pem'); //这是根据http://curl.haxx.se/ca/cacert.pem 下载的证书，添加这句话之后就运行正常了

  curl_setopt($ch, CURLOPT_URL, $url);
  if ($data) curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
  if ($header) curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
  curl_setopt($ch, CURLOPT_POST, true);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
  $response = curl_exec($ch);
  $error = curl_error($ch);
  curl_close($ch);
  if ($error) {
    if ($first) {
      return curl_https($url, $data, $header, $timeout, false);
    }
    die($error);
  }
  return $response;
}
$data = json_decode(file_get_contents('php://input'), true);
if (isset($data['getFile'])) {
  $file = curl_https($data['getFile']);

  mPrintX(["file" => base64_encode($file)]);
  die;
}
// $d = file_get_contents('php://input');

// mPrint([$_FILES, $_POST, file_get_contents('php://input')]);
// $d = $_FILES['audio']['tmp_name'];
// copy($d, './2.wav');
// die;
if (isset($data['wx'])) $_POST = $data;
// if (!$_POST) die();

$h5 = false;
if (isset($_POST['h5']) && isset($_FILES['audio']) && isset($_FILES['audio']['tmp_name'])) {
  $_POST['h5'] = json_decode($_POST['h5'], true);
  $_POST['h5']['file'] = $_FILES['audio']['tmp_name'];
  $h5 = true;
}
if (isset($_POST['wx']) || $h5) {
  // mPrintX($_POST);
  $t = true;
  if ($t) include_once('./cli_request.php');
  else include_once("./warrant/cli_request.php");
  die;
}

// 微信 JS 接口签名校验工具: https://mp.weixin.qq.com/debug/cgi-bin/sandbox?t=jsapisign
define('appid', "wx203cc77c39552399");
define('secret', "16b5b5b8adf5feb3ae01ee3b6cb18eaa");

class Cache {
  private $cache_path;
  //path for the cache
  private $cache_expire;
  //seconds that the cache expires

  //cache constructor, optional expiring time and cache path
  public function __construct($exp_time = 3600, $path = "cache/") {
    $this->cache_expire = $exp_time;
    $this->cache_path = dirname(__FILE__) . '/' . $path;
  }

  //returns the filename for the cache
  private function fileName($key) {
    return $this->cache_path . md5($key);
  }

  //creates new cache files with the given data, $key== name of the cache, data the info/values to store
  public function put($key, $data) {
    $values = serialize($data);
    $filename = $this->fileName($key);
    // mPrint($filename);
    // die;
    $file = fopen($filename, 'w');
    if ($file) { //able to create the file
      fwrite($file, $values);
      fclose($file);
    } else
      return false;
  }

  //returns cache for the given key
  public function get($key) {
    $filename = $this->fileName($key);
    if (!file_exists($filename) || !is_readable($filename)) { //can't read the cache
      return false;
    }
    if (time() < (filemtime($filename) + $this->cache_expire)) { //cache for the key not expired
      $file = fopen($filename, "r");
      // read data file
      if ($file) { //able to open the file
        $data = fread($file, filesize($filename));
        fclose($file);
        return unserialize($data);
        //return the values
      } else
        return false;
    } else
      return false;
    //was expired you need to create new
  }
}

function getSignature($jsapi_ticket, $noncestr, $timestamp, $url) {
  $string1 = "jsapi_ticket=" . $jsapi_ticket . "&noncestr=" . $noncestr . "&timestamp=" . $timestamp . "&url=" . $url;
  $sha1 = sha1($string1);
  return $sha1;
}

function getJsapi_ticket() {
  $cache = new Cache();
  $cache = new Cache(7000); //需要创建cache文件夹存储缓存文件。
  //从缓存从读取键值 $key 的数据
  $jsapi_ticket = $cache->get("jsapi_ticket");
  $access_token = getAccess_token();
  //如果没有缓存数据
  if ($jsapi_ticket == false) {
    $access_token = getAccess_token();
    $url = 'https://api.weixin.qq.com/cgi-bin/ticket/getticket';
    $data = array('type' => 'jsapi', 'access_token' => $access_token);
    $header = array();
    $response = json_decode(curl_https($url, $data, $header, 5));
    $jsapi_ticket = $response->ticket;
    //写入键值 $key 的数据
    $cache->put("jsapi_ticket", $jsapi_ticket);
  }
  return $jsapi_ticket;
}

function getAccess_token() {
  $cache = new Cache();
  $cache = new Cache(7000);
  //从缓存从读取键值 $key 的数据
  $access_token = $cache->get("access_token");

  //如果没有缓存数据
  if ($access_token == false) {
    $url = 'https://api.weixin.qq.com/cgi-bin/token';
    $data = array('grant_type' => 'client_credential', 'appid' => appid, 'secret' => secret);
    $header = array();

    $response = json_decode(curl_https($url, $data, $header, 5));
    $access_token = $response->access_token;
    //写入键值 $key 的数据
    $cache->put("access_token", $access_token);
  }
  return $access_token;
}

/** curl 获取 https 请求 
 * @param String $url 请求的url 
 * @param Array $data 要發送的數據 
 * @param Array $header 请求时发送的header 
 * @param int $timeout 超时时间，默认30s 
 */
// $url = 'https://file.api.weixin.qq.com/cgi-bin/media/get?access_token=33_9SBT60odusVuJF5UPIoykcI-IC5nfCpwNWqSdckPWDjBpLHSXcBKI2igYfBPbMAOQTMRfj-c9Q2baPqS26HVDsq9cRv27jtNU5kXtjHDhwJpH1Qud6Vb_TlG6r2tVIDsAoiWu0My7LRqLxN3NHAgAFAVPI&media_id=APyx7IyQ3HOV9enWm_lno-UNIaggiWYckrPREa7oGtk8aYUR-izsFs-SRd5Y84WN';
// $dt = curl_https($url);
// var_dump($dt);
// die;

$jsapi_ticket = getJsapi_ticket();
$nonceStr = "x" . rand(10000, 100000) . "x"; //随机字符串
$timestamp = time(); //时间戳

// $timestamp = 1590410643;
// $nonceStr = 'x92196x';

$url = $_POST['url'];
if (!$url) {
  $_POST = json_decode(file_get_contents('php://input'), true);
  $url = $_POST['url'];
}

$signature = getSignature($jsapi_ticket, $nonceStr, $timestamp, $url);
$result = [
  "jsapi_ticket" => $jsapi_ticket,
  "nonceStr" => $nonceStr,
  "timestamp" => $timestamp,
  "url" => $url,
  "signature" => $signature,
  'appId' => appid,
  'debug' => isset($_POST['debug']) && $_POST['debug'] == 'true' ? true : false,
  'token' => getAccess_token()
];
mPrintX($result);
